package cli;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

import au.com.bytecode.opencsv.CSVReader;

public class PM {
	public static void main(String[] args) {

		try {
			readLineByLineExample();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private static void readLineByLineExample() throws IOException {
		System.out.println("\n**** Mise en place base de données XML ****");
		String csvFilename = "/home/karim/workspace_1/PG220-Projet/evts.csv";
		CSVReader csvReader = new CSVReader(new FileReader(csvFilename), ';');
		String[] row1 = null;
		int k = 0, i=0;
		row1 = csvReader.readNext();

		Element db = new Element("db");
		Document doc = new Document(db);

		if (row1 != null){
			k = row1.length;
		}
		System.out.println("Nombre d'élements: "+k);

		Element evenement = new Element("evenements");


		// get root element and added student element as a child of it  
		doc.getRootElement().addContent(evenement);  

		String[] row = null;
		while ((row = csvReader.readNext()) != null) {
			Element manifestation = new Element("manifestation");
			manifestation.setAttribute(row1[0], row[0]);
			manifestation.setAttribute(row1[1],row[1]);
			evenement.addContent(manifestation);
			for (i=2; i < k; i++){
				if (!row[i].equals("")){
					manifestation.addContent(new Element(row1[i]).setText(row[i]));
				}
			}					
		}
		csvReader.close();

		Element reservation = new Element("reservations");
		doc.getRootElement().addContent(reservation);

		// get object to see output of prepared document  
		XMLOutputter xmlOutput = new XMLOutputter();  

		// passed fileWriter to write content in specified file  
		xmlOutput.setFormat(Format.getPrettyFormat());  
		xmlOutput.output(doc, new FileWriter("db.xml"));  

		System.out.println("File Saved!");
	}
}

